/**
 * 2019年2月17日下午2:49:16
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.TypeUtils;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.ShiroKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.entity.DanYuanEntity;
import com.baihang.project.ds.entity.LouDongEntity;
import com.baihang.project.ds.entity.TaoXingEntity;
import com.baihang.project.ds.model.FangYuanModel;

import redis.clients.jedis.Jedis;

/**
 * 用户所有操作都通过redis包括读取
 *
 */
@Service
public class FangYuanRedisService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(FangYuanRedisService.class);
	private Jedis jedis = RedisKit.getJedis();
	private static Object mutex = new Object();
	public List<LouDongEntity> getLouDong(){
		List<String> list = jedis.hvals("rooms");//取出所有房源
		List<FangYuanModel> model=new ArrayList<FangYuanModel>();
		for(int i=0;i<list.size();i++) {
			FangYuanModel model2 = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});
			model.add(model2);
		}
		//根据楼栋进行分组
				TreeMap<String,List<FangYuanModel>> louDongMap= model.stream().collect(Collectors.groupingBy(FangYuanModel::getD_BanName,TreeMap::new,Collectors.toList()));
				List<LouDongEntity>  loudonglist = new ArrayList<LouDongEntity>();//存放楼栋
				for (Entry<String, List<FangYuanModel>> entry : louDongMap.entrySet()) {
					LouDongEntity  louDongEty = new LouDongEntity();//1创建楼栋
					louDongEty.setName(entry.getKey());//楼栋名称
					List<FangYuanModel> danYuanModel = entry.getValue();//1-1 获取楼栋下的单元
					//根据单元进行分组
					TreeMap<String,List<FangYuanModel>> danYuanMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_Unit,TreeMap::new,Collectors.toList()));
					List<DanYuanEntity>  danYuanList = new ArrayList<DanYuanEntity>();//存放单元
					for(Entry<String,List<FangYuanModel>> entryDanYuan:danYuanMap.entrySet()) {
						DanYuanEntity danYuanEty = new DanYuanEntity();//2创建单元
						danYuanEty.setName(entryDanYuan.getKey());
						List<FangYuanModel> taoXingModel = entryDanYuan.getValue();//2-1 获取楼栋下的单元下面的套型
						//根据套型进行分组
						Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
						List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
						for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
							TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
							taoXingEty.setIndex(entryTaoXing.getKey());
							List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
							taoXingEty.setShiHaoList(shiHaoModel);
							taoXingList.add(taoXingEty);//加入套型
						}				
						danYuanEty.setTaoxingList(taoXingList);
						danYuanList.add(danYuanEty);
					}
					louDongEty.setDanyuanList(danYuanList);
					loudonglist.add(louDongEty);
				}
				return loudonglist;
	}
	
	//查询当前用户已经订购成功的套数
	public int alreadyBuyCount() {
		int count = 0;
		if(jedis.sismember("renchou", ShiroKit.getCurrentUser().getUserName())) {
			count=1;
		}
		return count;
	}
	
	//查看房源详情页
	public FangYuanModel getXiangQing(int id) {
		String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
		return model;
	}
	
	
	
	/**
	 * 获取当前用户收藏的房源id集     redis中增加userShouCang
	 */
	public String getShouCangFyIds() {
		String modelJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);

		StringBuilder sb = new StringBuilder("[");
		sb.append(modelJson);
		sb.append("]");
		System.err.println("收藏is="+sb.toString());
		return sb.toString();
	}
	//获取单元数据
	public List<DanYuanEntity> getDanYuan(String name){
		logger.info("redis获取单元");
		List<String> list = jedis.hvals("rooms");//取出所有房源
		List<FangYuanModel> model=new ArrayList<FangYuanModel>();
		for(int i=0;i<list.size();i++) {
			FangYuanModel model2 = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});
			model.add(model2);
		}
		//通过楼栋名进行过滤
		//List<FangYuanModel> danYuanModel = dao.queryForFangYuanList(String.format("select * from room where D_BanName ='%s'",name));
		List<FangYuanModel> danYuanModel = model.stream().filter(FangYuanModel->FangYuanModel.getD_BanName().equals(name)).collect(Collectors.toList());
		TreeMap<String,List<FangYuanModel>> danYuanMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_Unit,TreeMap::new,Collectors.toList()));
		List<DanYuanEntity>  danYuanList = new ArrayList<DanYuanEntity>();//存放单元
		for(Entry<String,List<FangYuanModel>> entryDanYuan:danYuanMap.entrySet()) {
			DanYuanEntity danYuanEty = new DanYuanEntity();//2创建单元
			danYuanEty.setName(entryDanYuan.getKey());
			List<FangYuanModel> taoXingModel = entryDanYuan.getValue();//2-1 获取楼栋下的单元下面的套型
			//根据套型进行分组
			Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
			List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
			for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
				TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
				taoXingEty.setIndex(entryTaoXing.getKey());
				List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
				taoXingEty.setShiHaoList(shiHaoModel);
				taoXingList.add(taoXingEty);//加入套型
			}				
			danYuanEty.setTaoxingList(taoXingList);
			danYuanList.add(danYuanEty);
		}
		return danYuanList;
	}
	//获取房源
	public List<TaoXingEntity> getTaoXing(String loudongName,String danyuanName){
		logger.info("redis获取房源");
		List<String> list = jedis.hvals("rooms");//取出所有房源
		List<FangYuanModel> model=new ArrayList<FangYuanModel>();
		for(int i=0;i<list.size();i++) {
			FangYuanModel model2 = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});
			model.add(model2);
		}
		//List<FangYuanModel> taoXingModel = dao.queryForFangYuanList(String.format("select * from room where D_BanName ='%s' and D_Unit='%s'",loudongName,danyuanName));
		List<FangYuanModel> taoXingModel = model.stream().filter(FangYuanModel->FangYuanModel.getD_BanName().equals(loudongName)).filter(FangYuanModel->FangYuanModel.getD_Unit().equals(danyuanName)).collect(Collectors.toList());
		Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
		List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
		for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
			TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
			taoXingEty.setIndex(entryTaoXing.getKey());
			List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
			taoXingEty.setShiHaoList(shiHaoModel);
			taoXingList.add(taoXingEty);//加入套型
		}			
		
		return taoXingList;
	}
	
	//推荐房源 从本人收藏的房源中取出未售房源中排第一的房源  新增加 userBuy  它是map key是房源id value是用户手机号
	public Record getTuiJian() {
		Record record = new Record();
		if(jedis.hexists("userShouCang", ShiroKit.getCurrentUser().getUserName())) {
			String modelJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
			if(StrKit.isNotEmpty(modelJson)) {
				if(modelJson.contains(",")) {
					String[]  scs= modelJson.split(",");
					for(int i=0;i<scs.length;i++) {
						if(jedis.hexists("userBuy", scs[i])) {//如果购买map包含了此房源id
							continue;
						}else {//没有则查出此房源
							String roomJson = jedis.hmget("rooms", scs[i]).get(0);
							JSONObject jsonObj = JSON.parseObject(roomJson);
							record.set("D_BanName", jsonObj.getString("D_BanName"));
							record.set("D_Unit", jsonObj.getString("D_Unit"));
							record.set("D_RoomNo", jsonObj.getString("D_RoomNo"));
							record.set("D_ID", jsonObj.getIntValue("D_ID"));
							break;
						}
					}									
				}else {//只有一个值
					if(jedis.hexists("userBuy", modelJson)) {//如果购买map包含了此房源id
						record = null;
					}else {//没有则查出此房源
						String roomJson = jedis.hmget("rooms", modelJson).get(0);
						JSONObject jsonObj = JSON.parseObject(roomJson);
						record.set("D_BanName", jsonObj.getString("D_BanName"));
						record.set("D_Unit", jsonObj.getString("D_Unit"));
						record.set("D_RoomNo", jsonObj.getString("D_RoomNo"));
						record.set("D_ID", jsonObj.getIntValue("D_ID"));
					}
				}
			}else {
				record=null;
			}
			
		}else {
			record=null;
		}
			
		return record;
	}
	//最终购房代码
	public String buyRoom(int id) {
		logger.info("抢购id="+id+"的房源");
		String result ="true";
		String msg="订购成功";
		synchronized (mutex)//互斥锁
        {
			//判断房源是否已售，
			if(jedis.hexists("userBuy", String.valueOf(id))) {//如果购买map包含了此房源id
				result="false";
				msg = "订购失败";
			}else {//没有则查出此房源
				String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
				FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
				if("1".equals(jedis.hmget("systemConfig","IsTest").get(0))) {//测试模式不需要生成订单号
					model.setD_state("2");
					model.setD_Operation(ShiroKit.getCurrentUser().getUserName());
					model.setD_SaleDate(DateKit.getCurrentDate(DateKit.Format_DateTime));
				}else {
					//订单号 日期+用户手机
					String ddh = String.format("%s%s", DateKit.getCurrentDate(DateKit.Format_DateTime2),ShiroKit.getCurrentUser().getUserName());
					String operationRemark =String.format("S:/%s", DateKit.getCurrentDate(DateKit.Format_DateTime));
					model.setD_state("2");
					model.setD_Operation(ShiroKit.getCurrentUser().getUserName());
					model.setD_SaleDate(DateKit.getCurrentDate(DateKit.Format_DateTime));
					model.setD_SerialNumber(ddh);
					model.setD_OperationRemark(operationRemark);
				}
				logger.info("更新购房json="+JSON.toJSONString(model));
				TypeUtils.compatibleWithFieldName = true;
				jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
				jedis.hset("rengou", ShiroKit.getCurrentUser().getUserName(), String.valueOf(id));
				jedis.hset("userBuy", String.valueOf(id),ShiroKit.getCurrentUser().getUserName());
				//jedis.sadd("rengou", ShiroKit.getCurrentUser().getUserName());//将认购成功的用户加入redis
			}      
        }
	
		return String.format("{\"result\":\"%s\",\"msg\":\"%s\"}", result,msg);
	}
	//查询房源状态
	public String getFangYuanState(int id) {
			String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
			FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});			
			return String.valueOf(model.getD_state());
	}
	
	//单个翻红
	public void singleFanHong(int id) {
		//直接变蓝
		String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
		model.setD_Monitor("2");
		TypeUtils.compatibleWithFieldName = true;
		jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
		//随机变红
		Random random = new Random();
		long bianhong = random.nextInt(30);
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
          
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                    	 try {							
								TimeUnit.SECONDS.sleep(bianhong);
								System.err.println(bianhong+"线程操作");
								
								String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
								FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
								model.setD_Monitor("3");
								jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
							
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
                    }
                });
	}
	
	public boolean updateHouseState() {
		//将项目状态变更为自然结束
		jedis.hset("systemConfig", "State", "6");
		
		return true;
	}
	
	/**
	 * 根据房源id 锁定房源。先查询房源状态，满足未售时才锁定
	 * @param roomId
	 * @return
	 */
	public String userYuDingRoom(int roomId) {
		String modelJson = jedis.hmget("rooms", String.valueOf(roomId)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
		String state = model.getD_state();
		String monitor = model.getD_Monitor();
		if(state.equals("0") && monitor.equals("0")) {
			model.setD_state("1");
			model.setD_Operation(ShiroKit.getCurrentUser().getUserName());
			model.setD_EditTime(DateKit.getCurrentDate(DateKit.Format_DateTime));
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(roomId), JSON.toJSONString(model));
			return JsonKit.toDoubleJson("true", "预定成功!");
			
		}else if(state.equals("1")||monitor.equals("1") ||monitor.equals("2")) {
			return JsonKit.toDoubleJson("false", "预定失败!此房源已预定!");
		}else {
			return JsonKit.toDoubleJson("false", "预定失败!此房源已售出!");
		}
	}
	
		//重置房源状态，预定还原为未售
		public void reSetState(int roomId) {
			String modelJson = jedis.hmget("rooms", String.valueOf(roomId)).get(0);
			FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
			model.setD_state("0");
			model.setD_Operation("");
			model.setD_EditTime(DateKit.getCurrentDate(DateKit.Format_DateTime));
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(roomId), JSON.toJSONString(model));
			
		}
		//将未售变为预定
		public void setState(int id) {
			String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
			FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
			model.setD_state("1");
			model.setD_Operation(ShiroKit.getCurrentUser().getUserName());
			model.setD_EditTime(DateKit.getCurrentDate(DateKit.Format_DateTime));
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
		}
		
	public static void main(String[] args) {
		Jedis jedis = RedisKit.getJedis();
		List<String> list = jedis.hvals("rooms");//取出所有房源
		List<FangYuanModel> modelList=new ArrayList<FangYuanModel>();
		for(int i=0;i<list.size();i++) {
			FangYuanModel model = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});
			modelList.add(model);
		}
		System.err.println(modelList.get(0).getD_BanName());
		
		/*String modelJson = jedis.hmget("rooms", String.valueOf(1000)).get(0);
		System.err.println(modelJson);
		TypeUtils.compatibleWithFieldName = true;
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
		model.setD_state("1");
		//model.setD_Operation("111");
		jedis.hset("rooms", String.valueOf(1060), JSON.toJSONString(model));*/
		
		/*FangYuanRedisService service = new FangYuanRedisService();
		List<LouDongEntity>  list = service.getLouDong();
		//System.err.println(list.get(0).getDanyuanList().get(0).getName());
		System.err.println(list.get(0).getDanyuanList().get(0).getTaoxingList().get(0).getShiHaoList().get(0).getD_ID());
		System.err.println(list.get(0).getDanyuanList().get(0).getTaoxingList().get(0).getShiHaoList().get(0).getD_BanName());
		System.err.println(list.get(0).getDanyuanList().get(0).getTaoxingList().get(0).getShiHaoList().get(0).getD_state());
		List<FangYuanModel> taoXingList = list.get(0).getDanyuanList().get(1).getTaoxingList().get(1).getShiHaoList();
		for(int i=0;i<taoXingList.size();i++) {
			System.err.println(taoXingList.get(i).getD_ID());
			System.err.println(taoXingList.get(i).getD_state());
		}*/
		
		/*List<String> list = jedis.hvals("rooms");
		StringBuilder sb = new StringBuilder("[");
		for(int i=0;i<list.size();i++) {
			sb.append(list.get(i)+",");
		}
		sb.delete(sb.length()-1, sb.length());
		sb.append("]");
		System.err.println(sb.toString());*/
		
		
	}
}
